import time
from watchdog.observers import Observer # 导入观察者
from watchdog.events import PatternMatchingEventHandler # 事件处理器

def on_created(event):
    print(f"创建了{event.src_path}。")

def on_deleted(event):
    print(f"注意，{event.src_path}被删除了。")

def on_modified(event):
    print(f"{event.src_path}被修改。")

def on_moved(event):
    print(f"文件从{event.src_path}移动到了{event.dest_path}")

def main():
    # 要处理文件的匹配规则，*表示匹配所有文件
    patterns = '*'
    # 不需要处理文件的匹配规则
    ignore_patterns = ''
    # 是否只监听常规文件，不包含目录，False表示目录本身也要监听
    ignore_directories = False
    # 设置为True表示区分路径大小写
    case_sensitive = True
    # 创建事件处理器
    evnet_handler = PatternMatchingEventHandler(patterns,
                                                ignore_patterns,
                                                ignore_directories,
                                                case_sensitive)
    evnet_handler.on_created = on_created
    evnet_handler.on_deleted = on_deleted
    evnet_handler.on_modified = on_modified
    evnet_handler.on_moved = on_moved

    # 要监听的路径
    path = "d1"
    # 是否要监听当前目录的子目录中文件发生的变化，True表示子目录的变化也监听
    recursive = True
    # 创建观察者
    observer = Observer()
    # evnet_handler 事件处理器
    observer.schedule(evnet_handler, path, recursive=recursive)

    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt: # Ctrl+c / Command+c 退出程序时
        observer.stop()
        observer.join()

main()